#include <Socket.h>

	
Socket::Socket()
{
	this->fd = socket(AF_INET, SOCK_STREAM, 0);
}
	
	
//绑定端口并指定接受的最大连接数
bool Socket::Listen(int port, int max)
{
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	if(bind(fd, (struct sockaddr*)&addr, sizeof(addr))  == -1)
	{
		return false;
	}
	
	if(listen(fd, max) == -1)
	{
		return false;
	}
	
	return true;
}


//连接某个服务地址
bool Socket::Connect(string address, int port)
{
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = inet_addr(address.c_str());
	if(connect(fd, (struct sockaddr*)&addr, sizeof(addr))  == -1)
	{
		return false;
	}
	return true;
}


//接受一个连接请求
Socket Socket::Accept()
{
	struct sockaddr_in addr;
	socklen_t length =  sizeof(addr);
	int con = accept(fd, (struct sockaddr*)&addr, &length);
	if(con >= 0)
	{
		Socket client;
		client.fd = con;
		return client;
	}else{
		throw "error receive connection";
	}
}

//从连接中读取数据
int Socket::Recv(char* buf, int size)
{
	
	/**
	>  0  成功接收数据大小。

 	=  0  另外一端关闭了套接字

 	= -1     错误，需要获取错误码errno
	*/
	return recv(fd, buf, size, 0);
}


//向连接中写入数据
int Socket::Send(char* buf, int size)
{
	
	return send(fd, buf, size, 0);
}
	
	

//主动关闭连接
void Socket::Close()
{
	close(fd);	
}


	
